package deployr.domain;

import static deployr.core.Files.*;
import static deployr.core.Streams.*;
import static java.text.MessageFormat.*;

import java.io.*;

public class Deliverables{

	private final String path;

	public Deliverables(String path) {
		this.path = path;
		mkdirUnlessExists(path);
	}

	public String getPath() {
		return path;
	}

	public Deliverable createDeliverable(String updateKey, String name, byte[] bytes) {
		return new Deliverable(updateKey, name, bytes);
	};

	public IDeliverable createAndAddUpdateDeliverable(String updateKey, String name, byte[] bytes) {
		Deliverable deliverable = createDeliverable(updateKey, name, bytes);
		write(deliverable);
		return deliverable;
	}

	private void write(Deliverable deliverable) {
		String path = pathTo(deliverable);
		mkdirUnlessExists(path);
		File file = new File(path, deliverable.getName());
		deliverable.writeTo(openOutputStreamOn(file));
	}

	private String pathTo(Deliverable deliverable) {
		String updateKey = deliverable.getUpdateKey();
		return format("{0}/{1}", getPath(), updateKey);
	}

}